import { HttpException, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { UserEntity } from './entities/user.entity';
import { JwtService } from '@nestjs/jwt';
import { Repository } from 'typeorm';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private userRepository: Repository<UserEntity>,
    private readonly jwtService: JwtService,
  ) {}
  async create(createUserDto: CreateUserDto) {
    console.log('createUserDto',createUserDto)
    let result = await this.userRepository.save(createUserDto);
    return result;
  }

  async findAll() {
    let result = await this.userRepository.find();
    // return `This action returns all user` + JSON.stringify(result);
    return { result };
  }

  async findOne(id: number) {
    let result = await this.userRepository.find({ where: { id: id } });
    // console.log(result);
    if (result.length == 0) {
      throw new HttpException('暂无数据', 401);
    }
    let token = await this.jwtService.signAsync({
      id: result[0].id,
      sub: true,
    });
    return {
      result,
      token,
    };
  }

  async update(id: number, updateUserDto: UpdateUserDto) {
    const qb = await this.userRepository.createQueryBuilder();
    updateUserDto = { ...updateUserDto, update_time: new Date().toISOString() };
    return await qb.update().set(updateUserDto).where({ id }).execute();
    //另一个方法
    // return await this.userRepository.update({ id }, updateUserDto);
  }

  async remove(id: number) {
    // 先获取用户实体
    const user = await this.userRepository.findOneBy({ id });
    if (!user) {
      throw new HttpException('用户不存在', 401);
    }
    // 使用 remove 方法删除实体
    return this.userRepository.remove(user);
  }
}
